export default class websocket {
  constructor(url,params) {
    this.url =  url;
    this.socket=null;
    this.isCreate = false; // WebSocket 是否创建成功
    this.isConnect = false; // 是否已经连接
    this.isInitiative = false; // 是否主动断开
    this.timeoutNumber = 3; // 心跳检测间隔
    this.heartbeatTimer = null; // 心跳检测定时器
    this.reconnectTimer = null; // 断线重连定时器
    this.againTime = 3; // 重连等待时间(单位秒)
    this.initSocket(params);
  }
  // 初始化webSocket连接
  initSocket(params) {
    this.socket = new WebSocket(this.url);
    this.socket.onopen = (event) => {
      console.log('socket已连接');
      this.isCreate = true;
      clearInterval(this.heartbeatTimer);
      clearTimeout(this.reconnectTimer);
      this.isConnect = true;
      this.heartbeatCheck()
    };
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if(params.onmessage){
        params.onmessage(data);
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket Error:', error);
    };

    this.socket.onclose = (event) => {
      console.log('WebSocket connection closed.');
      this.isConnect = false
      this.reconnect()
    };
  }
  // 开启心跳检测
  heartbeatCheck() {
    console.log('开启心跳')
    this.data = {
      type: "HEARTBEAT"
    }
    this.heartbeatTimer = setInterval(() => {
      this.sendMsg(this.data)
    }, this.timeoutNumber * 1000)
  }
  getMsg(data){
    return data;
  }
  sendMsg(data) {
    if (this.socket) {
      this.socket.send(JSON.stringify(data));
    }
  }
  // 重新连接
  reconnect() {
    // 停止发送心跳
    clearTimeout(this.reconnectTimer)
    clearInterval(this.heartbeatTimer)
    // 如果不是人为关闭的话，进行重连
    if (!this.isInitiative) {
      this.reconnectTimer = setTimeout(() => {
        this.initSocket()
      }, this.againTime * 1000)
    }
  }
  // 关闭 WebSocket 连接
  closeSocket() {
    this.data = null
    this.isCreate = false
    this.isConnect = false
    this.isInitiative = true
    this.socketExamples = null
    clearInterval(this.heartbeatTimer)
    clearTimeout(this.reconnectTimer)
    console.log('关闭 WebSocket 成功')
    this.socket.close();
  }
}
